import React from 'react';
import { Text, View, StyleSheet, Image, FlatList, ToastAndroid, NativeModules } from 'react-native';
import { observer, inject } from 'mobx-react';
import SafeAreaViewPlus from '../components/base/SafeAreaViewPlus';
import BackPressComponent from '../components/base/BackPress';
import GlobalStyles from '../style/GlobalStyles';
import Button from '../components/base/Button';
import NavigationUtil from '../navigation/NavigationUtil';
import px from '../utils/px';

@inject(['VersionStore'])
@observer
export default class VersionScreen extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            // 程序强制更新中
            forceUpdating: false
        };
        // 绑定路由
        NavigationUtil.navigation = this.props.navigation;
        this.backPress = new BackPressComponent({ backPress: () => this.onBackPress() });
    }

    // 配置 Navigation 设置
    static navigationOptions = {
        title: '版本控制页',
        header: null
    };

    // 监听安卓返回键
    onBackPress = () => {
        // 最近2秒内按过back键，可以退出应用。
        if (this.lastBackPressed && this.lastBackPressed + 2000 >= Date.now())
            return false;
        this.lastBackPressed = Date.now();
        ToastAndroid.show('再按一次退出应用', ToastAndroid.SHORT);
        return true;
    };

    // 立即更新
    handleUpdateNow() {
        const { version } = this.props.VersionStore;
        /**
         * @param {string} url - Apk 下载的服务器地址
         * @param {string} name - Apk 下载名称
         * @param {function} callback - 触发下载的回调函数
         */
        NativeModules.DownloadApk.downloading(version.updateUrl, "app-release.apk");
        version.isForce ? this.setState({ forceUpdating: true }) : NavigationUtil.goPage('Index');
    }

    // 稍候版本更新
    handleUpdateLate() {
        console.log('稍候版本更新');
        const { version } = this.props.VersionStore;
        const date = Date.now();
        const data = {
            lateVersion: version.logicVersion,
            lateTime: date
        };
        global.storage.save({ key: 'lateVersion', data, expires: null });
        NavigationUtil.goPage('Index');
    }

    // 取消版本更新
    handleUpdateCancel() {
        console.log('取消版本更新');
        const { version } = this.props.VersionStore;
        const data = {
            cancelVersion: version.logicVersion,
            isCancel: 1
        };
        global.storage.save({ key: 'cancelVersion', data, expires: null });
        NavigationUtil.goPage('Index');
    }

    componentDidMount() {
        NavigationUtil.willFocus(() => {
            this.backPress.componentDidMount();
        });
        NavigationUtil.willBlur(() => {
            this.backPress.componentWillUnmount();
        });
    }

    // 非强制更新的底部渲染
    getUpdateBottom() {
        return (
            <View style={styles.updateBtn}>
                <View style={styles.btnTop}>
                    <Button.NativeFeedback
                        btnStyle={[styles.btnLeft]}
                        btnText={[styles.btnLeftText]}
                        title={'稍后再说'}
                        onPress={() => this.handleUpdateLate()}
                    />
                    <Button.NativeFeedback
                        btnStyle={[styles.btnRight]}
                        title={'立即更新'}
                        onPress={() => this.handleUpdateNow()}
                    />
                </View>
                <View style={styles.btnBottm}>
                    <Text onPress={() => this.handleUpdateCancel()}>
                        忽略此版本
                    </Text>
                </View>
            </View>
        );
    }

    // 强制更新中的底部渲染
    getUpdateForceBottom() {
        return (
            <View style={styles.updateForceBtn}>
                <Button.NativeFeedback
                    btnStyle={[styles.forceBtnStyle]}
                    title={'立即更新'}
                    onPress={() => this.handleUpdateNow()}
                />
            </View>
        );
    }

    // 是否强制更新中中...
    isForceUpdating() {
        return (
            <View style={styles.bottom}>
                <Text style={styles.updating}>稍等片刻，马上就好</Text>
            </View>
        )
    }
    // 显示底部更新信息
    updateList() {
        const { messages, version } = this.props.VersionStore;
        return (
            <View style={styles.bottom}>
                <Text style={styles.updateTitle}>更新内容</Text>
                <View style={styles.updateList}>
                    <FlatList
                        data={messages}
                        renderItem={({ item }) => (
                            <Text style={styles.updateText}>
                                {item}
                            </Text>
                        )}
                        keyExtractor={(item, index) =>
                            index.toString()
                        }/>
                </View>
                {version.isForce
                    ? this.getUpdateForceBottom()
                    : this.getUpdateBottom()}
            </View>
        );
    }

    render() {
        const { forceUpdating } = this.state;
        const { version } = this.props.VersionStore;
        return (
            <SafeAreaViewPlus>
                <View style={styles.container}>
                    <View style={styles.versionBox}>
                        <View style={styles.headerTitle}>
                            <Text style={styles.headerTitleText}>
                                {forceUpdating ? '正在更新中...' : '发现新版本'}
                            </Text>
                            <Text style={styles.version}>{forceUpdating ? '' : version.version}</Text>
                        </View>
                        <Image
                            style={styles.header}
                            source={require('../assets/images/layer-head.png')}/>
                        {forceUpdating ? this.isForceUpdating() : this.updateList()}
                    </View>
                </View>
            </SafeAreaViewPlus>
        );
    }
}

const styles = StyleSheet.create({
    container: {
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        width: GlobalStyles.DEVICE_WIDTH,
        height: GlobalStyles.DEVICE_HEIGHT,
        backgroundColor: 'rgba(0, 0, 0, 0.7)'
    },
    versionBox: {
        width: px(586),
        backgroundColor: '#fff',
        position: 'relative',
        borderRadius: px(15)
    },
    headerTitle: {
        position: 'absolute',
        top: px(140),
        left: px(50),
        zIndex: 10
    },
    headerTitleText: {
        color: '#fff',
        fontSize: px(46),
        fontFamily: GlobalStyles.FONT_FAMILY_NORMAL
    },
    version: {
        color: '#fff',
        fontSize: GlobalStyles.FONT_SIZE,
        fontFamily: GlobalStyles.FONT_FAMILY_NORMAL
    },
    header: {
        width: '100%',
        height: px(329),
        backgroundColor: 'rgba(0, 0, 0, 0.7)',
        borderRadius: px(15)
    },
    bottom: {
        padding: px(35),
        borderBottomLeftRadius: px(15),
        borderBottomRightRadius: px(15),
        backgroundColor: '#fff'
    },
    updateTitle: {
        paddingLeft: px(10),
        color: GlobalStyles.TEXT_COLOR,
        fontSize: GlobalStyles.FONT_SIZE,
        fontFamily: GlobalStyles.FONT_FAMILY_NORMAL,
        paddingBottom: px(30)
    },
    updateList: {
        maxHeight: px(200),
        width: '100%',
        overflow: 'hidden'
    },
    updateText: {
        paddingLeft: px(10),
        color: GlobalStyles.TEXT_COLOR,
        fontSize: GlobalStyles.FONT_SIZE,
        paddingBottom: px(10),
        fontFamily: GlobalStyles.FONT_FAMILY_NORMAL
    },
    updateBtn: {
        width: '100%',
        marginTop: px(30)
    },
    btnTop: {
        width: '100%',
        display: 'flex',
        flexDirection: 'row',
        justifyContent: 'space-between'
    },
    btnLeft: {
        height: px(90),
        width: px(240),
        backgroundColor: 'rgb(238, 238, 238)',
        borderRadius: px(8)
    },
    btnLeftText: {
        color: '#333'
    },
    btnRight: {
        height: px(90),
        width: px(240),
        borderRadius: px(8)
    },
    btnBottm: {
        width: '100%',
        marginTop: px(30),
        alignItems: 'center'
    },
    updateForceBtn: {
        marginTop: px(10),
        width: '100%'
    },
    forceBtnStyle: {
        width: '100%',
        height: px(90),
        borderRadius: px(8)
    },
    updating: {
        width: '100%',
        textAlign: 'center',
        fontSize: GlobalStyles.FONT_SIZE,
        color: GlobalStyles.MAIN_COLOR,
    }
});
